-- UISkyActivityExchangeMulti
-- Created by chendh
-- 天空活动批量兑换界面

UISkyActivityExchangeMulti = class("UISkyActivityExchangeMulti", function()
    return cc.Layer:create();
end);

function UISkyActivityExchangeMulti.create(activityId, goodsId)
    return UISkyActivityExchangeMulti.new(activityId, goodsId);
end

-- 内部函数声明
local resize;

-- 构造函数
function UISkyActivityExchangeMulti:ctor(activityId, goodsId)
    self:setName("UISkyActivityExchangeMulti");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/item/BuyFood.csb");
    self:addChild(node);
    self.node = node;

    -- 记录商品信息
    self.activityId = activityId;
    self.goodsId = goodsId;

    if DungeonM.isInDungeon() then
        -- 迷宫中层级要调高
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 11);
    end

    -- 更换背景底图
    local up1 = findChildByName(self.node, "CT/bg_type");
    local up2 = findChildByName(self.node, "CT/bg_type2")
    up1:loadTexture(getTitleBgIconPath("pet"));
    up2:loadTexture(getTitleBgIconPath("pet"))
    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册各种点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 注册点击事件
function UISkyActivityExchangeMulti:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyActivityExchangeMulti");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 购买个数
    local str = getLocStr("btn_text_exchange_multi");
    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price1_btn");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(10);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 10));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price2_btn");
    local function onBuyClick2(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(1);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick2);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 1));
end

-- 注册事件处理回调函数
function UISkyActivityExchangeMulti:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UISkyActivityExchangeMulti");
        elseif ev == "enter" then

        end
    end);

    -- 关注活动关闭事件
    EventMgr.register("UISkyActivityExchangeMulti", event.ACTIVITY_CLOSE, function(args)
        -- 如果是当前活动关闭了，那么退出界面
        if self.activityId == args["id"] then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyActivityExchangeMulti");
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyActivityExchangeMulti", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UISkyActivityExchangeMulti" then
            -- TopMenu显示天空活动的数据和袭击次数
            local uiTopMenu = UIMgr:getCurrentScene().topMenu;
            uiTopMenu:setSkyActivityId(self.activityId);
            uiTopMenu:show(TOPMENU_FRAME_ACTIVITY_DATA, TOPMENU_FRAME_ACTIVITY_TIMES, TOPMENU_FRAME_HEAD_AIRSHIP);
        end
    end);

    -- 关注购买商品的事件
    EventMgr.register("UISkyActivityExchangeMulti", event.ACTIVITY_EXCHANGE, function(args)
        self:redraw();
    end);
end

-- 重绘
function UISkyActivityExchangeMulti:redraw()
    local goodsInfo;
    local itemId;
    local price;
    local value;

    -- 获取商品信息
    goodsInfo = SkyActivityM.queryExchange(self.goodsId);
    local bonusInfo = goodsInfo["bonus"];
    itemId = bonusInfo[2];

    value  = SkyActivityM.calcExchangeCostNum(self.activityId, self.goodsId);

    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");

    local nameLabel = CT:getChildByName("title");
    local subHeadLabel = findChildByName(self.node, "CT/subhead");

    nameLabel:setString(ItemM.query(itemId, "name"));
    TextStyleM.setTitleStyle(nameLabel);

    -- 当前拥有的数量
    -- local itemAmount = ItemM.getAmount(ME.user, itemId);
    -- TextStyleM.setSubheadStyle(subHeadLabel);
        -- 先停止滚动
    if self.scrollingData and self.scrollingData.classId ~= itemId then
        stopScrolling(subHeadLabel);
    end

    -- 当前拥有的数量
    TextStyleM.setSubheadStyle(subHeadLabel);
    local curAmount = ItemM.getAmount(ME.user, itemId);
    local scrollingData = self.scrollingData;

    -- 没有滚动过
    if not scrollingData or scrollingData.classId ~= itemId then
        subHeadLabel:setString(string.format(getLocStr("own_num"), ItemM.getAmount(ME.user, itemId)));
        self.scrollingData = {
            ["lastAmount"] = curAmount,
            ["classId"]    = itemId,
        };
    else
        -- 滚动
        numScrolling(subHeadLabel, getLocStr("own_num"), scrollingData.lastAmount, curAmount, 30);

        scrollingData.lastAmount = curAmount;
    end

    -- --  拥有%d件
    -- subHeadLabel:setString(string.format(getLocStr("own_num"), itemAmount));
    -- TextStyleM.setSubheadStyle(subHeadLabel);

    -- 显示商品价格
    local priceNode1 = findChildByName(self.node, "CT/price1");
    local priceNode2 = findChildByName(self.node, "CT/price2");

    local priceLabel1 = findChildByName(priceNode1, "price_label");

    TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    priceLabel1:setString(tostring(value * 10));

    -- 购买一个时的价格
    local priceLabel2 = findChildByName(priceNode2, "price_label");

    TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    priceLabel2:setString(tostring(value));

    -- 获取金钱
    -- 获取当前用户的金币数量
    local btnBuy1 = findChildByName(self.node, "CT/price1_btn");
    local btnBuy2 = findChildByName(self.node, "CT/price2_btn");


    local activityData = SkyActivityM.getActivityData(self.activityId) or {};
    local medalClassId  = SkyActivityM.query(self.activityId, "medal_class_id");
    local ownAmount = ItemM.getAmount(ME.user, medalClassId);

    if ownAmount >= value*10 then
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBuy1:setBright(true);
        btnBuy1:setTouchEnabled(true);
    else
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true);
        btnBuy1:setBright(false);
        btnBuy1:setTouchEnabled(false);
    end

    if ownAmount >= value then
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBuy2:setBright(true);
        btnBuy2:setTouchEnabled(true);
    else
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true);
        btnBuy2:setBright(false);
        btnBuy2:setTouchEnabled(false);
    end

    -- 显示价格对应的背景
    local priceBg2 = findChildByName(priceNode2, "price_bg");
    local priceBg1 = findChildByName(priceNode1, "price_bg");

    local gemBg1 = findChildByName(priceNode1, "gem_bg");
    local gemBg2 = findChildByName(priceNode2, "gem_bg");

    priceBg1:setVisible(true);
    priceBg2:setVisible(true);
    gemBg1:setVisible(false);
    gemBg2:setVisible(false);
    priceBg1:loadTexture(getCompoundItemIconPath("medal_bg"));
    priceBg2:loadTexture(getCompoundItemIconPath("medal_bg"));

    --
    local item = findChildByName(self.node, "CT/item");

    -- 物品图标
    local iconImg = findChildByName(item, "icon");
    iconImg:loadTexture(getItemIconPath(ItemM.query(itemId, "icon")));

    -- 物品星级
    local starNode = findChildByName(item, "star_node");
    local rank = ItemM.query(itemId, "rank");
    local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
    if layer then
        starNode:removeAllChildren();
        starNode:addChild(layer);
    end

    -- 物品的背景框
    local frameImage = findChildByName(item, "bg");
    frameImage:loadTexture(getFrameBgIconPath("rank", 1));
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UISkyActivityExchangeMulti:tryBuy(amount)
    -- 判断能否购买
    local ret = SkyActivityM.canExchange(self.activityId, self.goodsId, amount);
    if ret ~= true then
        AudioM.playFx("market_buy_failed");
        if ret == "sold_out" then
            -- 商品已售完
            alert(getLocStr("goods_sold_out"));
        elseif string.endWith(ret, "_lack") then
            -- 属性不足
            local field = string.sub(ret, 1, -6);
            if field == "gem" then
                showGemLackConfirm();
            else
                local fieldName;
                if string.startWith(field, "item_") then
                    local classId = tonumber(string.sub(field, 6, -1));
                    fieldName = ItemM.query(classId, "name");
                else
                    fieldName = FieldsM.getFieldName(field);
                end

                local msg = string.format(getLocStr("fail_to_do_operate"), fieldName, getLocStr("exchange"));
                alert(msg);
            end
        else
            -- 未知原因
            cclog("购买商品失败，原因：" .. ret );
        end
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UISkyActivityExchangeMulti");
        return;
    end

    Operation.cmd_sc_activity_exchange(self.activityId, self.goodsId, amount);
end